package org.lzy.shop.theme

import android.app.Activity
import android.graphics.Color
import android.view.LayoutInflater
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import org.lzy.shop.R
import org.lzy.shop.adapter.ThemeAdapter
import org.lzy.shop.datas.ThemeColorBean
import org.lzy.shop.theme.ThemeManager

class ThemeColorSelector(
    private val activity: Activity,
    private val onThemeApplied: (ThemeColorBean) -> Unit) {

    // 预设主题颜色列表
    private val themeColors = listOf(
        ThemeColorBean(0, "蓝色", Color.parseColor("#2196F3")),
        ThemeColorBean(1, "红色", Color.parseColor("#F44336")),
        ThemeColorBean(2, "绿色", Color.parseColor("#4CAF50")),
        ThemeColorBean(3, "橙色", Color.parseColor("#FF9800")),
        ThemeColorBean(4, "紫色", Color.parseColor("#9C27B0")),
        ThemeColorBean(5, "青色", Color.parseColor("#00BCD4")),
        ThemeColorBean(6, "灰色", Color.parseColor("#9E9E9E")),
        ThemeColorBean(7, "黑色", Color.parseColor("#212121"))

    )
    private val bottomSheetDialog by lazy {
        BottomSheetDialog(activity)
    }
    /**
     * 显示主题颜色选择弹窗
     */
    fun show() {
        val view = LayoutInflater.from(activity).inflate(R.layout.dialog_choosetheme, null)
        val recyclerView = view.findViewById<RecyclerView>(R.id.theme_colors_recycler_view)
        val cancelButton = view.findViewById<TextView>(R.id.cancel_button)
        val confirmButton = view.findViewById<TextView>(R.id.confirm_button)

        // 初始化RecyclerView
        recyclerView.layoutManager =
            LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)

        // 获取当前选中的主题ID
        val currentThemeId = ThemeManager.getCurrentThemeId()

        // 创建适配器
        // 创建适配器
        val adapter = ThemeAdapter(
            themeColors,
            currentThemeId
        ) { themeColor ->
            // 选择主题后立即应用
            applyTheme(themeColor)
            bottomSheetDialog.dismiss()
        }

        recyclerView.adapter = adapter

        // 设置取消按钮点击事件
        cancelButton.setOnClickListener {
            bottomSheetDialog.dismiss()
        }

        // 设置确认按钮点击事件（可选）
        confirmButton.setOnClickListener {
            bottomSheetDialog.dismiss()
        }

        // 显示弹窗
        bottomSheetDialog.setContentView(view)
        bottomSheetDialog.show()
    }

    /**
     * 应用选择的主题
     */
    private fun applyTheme(themeColor: ThemeColorBean) {
        // 保存主题选择
        ThemeManager.saveThemeSelection(activity, themeColor.id, themeColor.colorValue)

        // 应用主题到Activity
        if (activity is AppCompatActivity) {
            ThemeManager.applyThemeToActivity(activity, themeColor.colorValue)
        }

        // 通知回调
        onThemeApplied(themeColor)
    }
}